package com.yinhai.message.manage.register.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yinhai.core.app.api.util.ServiceLocator;
import com.yinhai.core.app.ta3.web.controller.BaseController;
import com.yinhai.core.common.api.base.IPage;
import com.yinhai.core.common.api.dto.IDto;
import com.yinhai.core.common.api.util.StringUtil;
import com.yinhai.core.common.ta3.dto.TaParamDto;
import com.yinhai.message.manage.register.bpo.IAppConfigBpo;
import com.yinhai.message.manage.register.po.AppConfigPo;
import com.yinhai.message.manage.register.vo.AppConfigVo;
import com.yinhai.message.manage.sysapp.bpo.ISysAppBpo;
import com.yinhai.message.manage.sysapp.vo.SysAppVo;

/**
*APP配置控制器
*@author lanyc
*@version created: 2017年4月4日上午11:06:40
*/
@RequestMapping("app")
@Controller
public class AppConfigController extends BaseController {
	@Resource
	private IAppConfigBpo appConfigBpo;
	
	@RequestMapping("AppConfigController!appConfig.do")
	public String appConfig(){
		return "manage/config/app/appConfig";
	}
	
	/**
	 * 查询全部app配置
	 * @return
	 */
	@RequestMapping("AppConfigController!queryAllAppConfig.do")
	public String queryAllAppConfig(){
		List<AppConfigVo> list = reFreshedAppConfigs();
		setList("appgrid", list);
		return JSON;
	}
	
	/**
	 * 分页查询全部app配置
	 * @return
	 */
	@RequestMapping("AppConfigController!queryAllAppConfigByPage.do")
	public String queryAllAppConfigByPage(){
		reFreshedAppConfigs();
		TaParamDto dto = getTaDto();
		int start = dto.getStart("appgrid");
		int limit = dto.getLimit("appgrid");
		IPage page = appConfigBpo.queryAllAppConfigByPage(dto,start,limit,"appgrid");
		setList("appgrid", page);
		return JSON;
	}
	
	/**
	 * appKey验重
	 * @return
	 */
	@RequestMapping("AppConfigController!checkAppKey.do")
	public String checkAppKey(){
		TaParamDto dto = getTaDto();
		AppConfigVo acv = appConfigBpo.queryAppCfgByAppKey(dto.getAsString("appKey"));
		if(!ObjectUtils.isEmpty(acv)){
			setMessage("app配置已存在!","error");
			setData("appKey","");
		}
		return JSON;
	}
	
	/**
	 * 刷新所有APP配置
	 * 由于接入系统可能会修改通信渠道，当其取消APP渠道后，APP配置应该移除相应的接入系统
	 * @return List<AppConfigVo> 刷新后的APP配置
	 */
	private List<AppConfigVo> reFreshedAppConfigs(){
		List<AppConfigVo> list = appConfigBpo.queryAllAppConfig();
		for (AppConfigVo acv : list) {
			if(StringUtil.isNotEmpty(acv.getSid())){
				String[] sids = acv.getSid().trim().split(",");
				String[] systemIds = acv.getSystemId().trim().split(",");
				String[] systemNames = acv.getSystemName().trim().split(",");
				ISysAppBpo sab = (ISysAppBpo) ServiceLocator.getService("sysAppBpo");
				//查看该接入系统的通信渠道中APP一项是否被删除
				for (int i=0;i<sids.length;i++) {
					SysAppVo sav = sab.getSysAppById(sids[i]);
					if(sav!=null){
						String type = sav.getSenderTypeOrder();
						//如果APP通信渠道被移除
						if(type==null||!type.contains("4")){
							sids[i]="";
							systemIds[i]="";
							systemNames[i]="";
						}
					//如果整个接入系统都被删除
					}else{
						sids[i]="";
						systemIds[i]="";
						systemNames[i]="";
					}
				}
				//重新拼接接入系统id，接入系统名称
				StringBuilder sb = new StringBuilder();
				StringBuilder sb1 = new StringBuilder();
				StringBuilder sb2 = new StringBuilder();
				for (int i = 0; i < sids.length; i++) {
					if(sids[i]!=null&&sids[i]!=""){
						sb.append(sids[i]+",");
						sb1.append(systemIds[i]+",");
						sb2.append(systemNames[i]+",");
					}
				}
				//如果sid和遍历之前对比发生了变化，则需要更新数据库
				if(!acv.getSid().equals(sb)){
					acv.setSid(sb.toString());
					acv.setSystemId(sb1.toString());
					acv.setSystemName(sb2.toString());
					
					AppConfigPo acp = new AppConfigPo();
					acp = acv.toPO(acp);
					appConfigBpo.updateAppConfig(acp);
				}
			}
		}
		return list;
	}
	
	/**
	 * 打开增加app配置页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("AppConfigController!toAddAppConfig.do")
    public String toAddAppConfig() throws Exception {
		reFreshedAppConfigs();
		setList("unDistrbutedSystem", getUnDistrbutedSystem());
		return "manage/config/app/appConfigAdd";
	}
	
	/**
	 * 获取未分配的接入系统
	 * @return List<SysAppVo> 未分配的含有APP渠道的接入系统VO
	 */
	private List<SysAppVo> getUnDistrbutedSystem(){
		ISysAppBpo sab = (ISysAppBpo) ServiceLocator.getService("sysAppBpo");
		//获取所有接入系统
		List<SysAppVo> list = sab.getSysAppList();
		//存储含有APP渠道的接入系统
		List<SysAppVo> SystemHasApp = new ArrayList<SysAppVo>();
		for (SysAppVo sav : list) {
			if(StringUtil.isNotEmpty(sav.getSenderTypeOrder())){
				String[] types = sav.getSenderTypeOrder().trim().split(",");
				if(types.length>0){
					for (String s : types) {
						//如果通信渠道有APP
						if("4".equals(s)){
							SystemHasApp.add(sav);
							break;
						}
					}
				}
			}
		}
		//获取所有APP配置里已分配的接入系统
		List<AppConfigVo> appCfgs = appConfigBpo.queryAllAppConfig();
		HashSet<String> set = new HashSet<String>();
		for (AppConfigVo acv : appCfgs) {
			if(acv.getSystemId()==null){
				continue;
			}
			String[] systemids = acv.getSystemId().trim().split(",");
			for (int i = 0; i < systemids.length; i++) {
				if(systemids[i]!=null){
					set.add(systemids[i]);
				}
			}
		}
		//获取尚未分配的接入系统
		List<SysAppVo> unDistrubited = new ArrayList<SysAppVo>();
		for (SysAppVo sav : SystemHasApp) {
			if(!set.contains(sav.getSystemid())){
				unDistrubited.add(sav);
			}
		}
		return unDistrubited;
	}
	
	/**
	 * 保存app配置
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("AppConfigController!addAppConfig.do")
	public String addAppConfig() throws Exception {
		TaParamDto dto = getTaDto();
		//准备PO对象
		AppConfigPo acp = getAppConfigPo(dto);
		//如果增加成功，清空输入框
		try{
			appConfigBpo.addAppConfig(acp);
			setTopMsg("新增成功!");
			setData("appKey","");
			setData("masterSecret","");
			setData("testRegistrationId","");
			List<SysAppVo> list = getUnDistrbutedSystem();
			List list1 = new ArrayList();
			setList("unDistrbutedSystem", list);
			setList("distrbutedSystem", list1);
		}catch(IllegalArgumentException e){
			//不成功，保留输入
			setMessage("appKey格式有误!","error");
		}
		return JSON;
	}
	
	/**
	 * 根据前台传入的值准备AppConfigPo对象
	 * @param dto
	 * @return AppConfigPo 封装好的AppConfigPo对象
	 */
	private AppConfigPo getAppConfigPo(TaParamDto dto){
		AppConfigPo acp = new AppConfigPo();
		acp.setAppKey(dto.getAsString("appKey"));
		acp.setMasterSecret(dto.getAsString("masterSecret"));
		acp.setTestRegistrationId(dto.getAsString("testRegistrationId"));
		String defaultApp = dto.getAsString("defaultApp");
		//获取接入系统信息
		StringBuilder systemids = new StringBuilder();
		StringBuilder systemnames = new StringBuilder();
		StringBuilder sids = new StringBuilder();
		
		List<IDto> list = (List<IDto>) getGridSelected("distrbutedSystem");
		for (IDto iDto : list) {
			sids.append(iDto.getAsString("id")+",");
			systemids.append(iDto.getAsString("systemid")+",");
			systemnames.append(iDto.getAsString("systemname")+",");
		}
		acp.setSid(sids.toString());
		acp.setSystemId(systemids.toString());
		acp.setSystemName(systemnames.toString());
		
		if(defaultApp!=null&&"da".equals(defaultApp)){
			acp.setDefaultApp(1);
		}else{
			acp.setDefaultApp(0);
		}
		return acp;
	}
	
	/**
	 * 打开编辑app配置页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("AppConfigController!toEditAppConfig.do")
	public String toEditAppConfig() throws Exception {
		reFreshedAppConfigs();
		TaParamDto dto = getTaDto();
		String appKey = dto.getAsString("appKey");
		AppConfigVo acv = appConfigBpo.queryAppCfgByAppKey(appKey);
		setData("appKey",acv.getAppKey());
		setData("testRegistrationId",acv.getTestRegistrationId());
		setData("masterSecret",acv.getMasterSecret());
		Integer defautlApp = acv.getDefaultApp();
		if(defautlApp!=null&&defautlApp==1){
			setData("defaultApp","da");
		}
		//设置已分配到当前APP的接入系统
		if(StringUtil.isNotEmpty(acv.getSystemId())&&StringUtil.isNotEmpty(acv.getSystemName())){
			String[] ids = acv.getSid().trim().split(",");
			String[] systemids = acv.getSystemId().trim().split(",");
			String[] systemnames = acv.getSystemName().trim().split(",");
			ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
			for (int i = 0; i < systemids.length; i++) {
				if(StringUtil.isNotEmpty(systemids[i])){
					HashMap<String,String> map = new HashMap<String,String>();
					map.put("id",ids[i]);
					map.put("systemid", systemids[i]);
					map.put("systemname", systemnames[i]);
					list.add(map);
				}
			}
			setList("distrbutedSystem", list);
		}
		
		//设置还未分配的系统
		setList("unDistrbutedSystem",getUnDistrbutedSystem());
		return "manage/config/app/appConfigEdit";
	}
	
	/**
	 * 更改APP配置
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("AppConfigController!updateAppConfig.do")
	public String updateAppConfig(){
		TaParamDto dto = getTaDto();
		AppConfigPo acp = getAppConfigPo(dto);
		//保存APP信息
		appConfigBpo.updateAppConfig(acp);
		setTopMsg("修改成功");
		return JSON;
	}
	
	/**
	 *删除APP配置
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("AppConfigController!deleteAppConfig.do")
	public String deleteAppConfig(){
		TaParamDto dto = getTaDto();
		String appKey = dto.getAsString("appKey");
		appConfigBpo.deleteAppConfig(appKey);
		return JSON;
	}
	
	/**
	 *验证App配置
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("AppConfigController!validateAppConfig.do")
	public String validateAppConfig(){
		TaParamDto dto = getTaDto();
		try{
			appConfigBpo.validateAppConfig(dto.getAsString("appKey"),dto.getAsString("masterSecret"),dto.getAsString("testRegistrationId"));
		}catch(IllegalArgumentException e){
		}
		return JSON;
	}
	
	/**
	 * 批量增加接入系统
	 */
	@RequestMapping("AppConfigController!batchAddSystem.do")
	public String batchAddSystem(){
		TaParamDto dto = getTaDto();
		List s = getJsonStrToList(dto.getAsString("selected"));
		List all = getJsonStrToList(dto.getAsString("all"));
		List otherAll = getJsonStrToList(dto.getAsString("otherAll"));
		//将选择的接入系统增加到已分配中
		otherAll.addAll(s);
		//将选择的接入系统移出未分配
		all.removeAll(s);
		
		List forClear = new ArrayList();
		//将已分配、未分配接入系统清空
		setList("distrbutedSystem", forClear);
		setList("unDistrbutedSystem", forClear);
		
		setList("distrbutedSystem", otherAll);
		setList("unDistrbutedSystem", all);
		return JSON;
	}
	
	/**
	 * 批量移除接入系统
	 */
	@RequestMapping("AppConfigController!batchDeleteSystem.do")
	public String batchDeleteSystem(){
		TaParamDto dto = getTaDto();
		List s = getJsonStrToList(dto.getAsString("selected"));
		List all = getJsonStrToList(dto.getAsString("all"));
		List otherAll = getJsonStrToList(dto.getAsString("otherAll"));
		
		//将选择的增加到未分配
		otherAll.addAll(s);
		//将选择的移出到已分配
		all.removeAll(s);
		
		List forClear = new ArrayList();
		setList("distrbutedSystem", forClear);
		setList("unDistrbutedSystem", forClear);
		
		setList("distrbutedSystem", all);
		setList("unDistrbutedSystem", otherAll);
		return JSON;
	}
	
}